import React from 'react';
import { connect } from 'dva';
import { Picker,Drawer, List, NavBar,Icon, InputItem , TabBar,Pagination ,Toast ,Button,TextareaItem,WhiteSpace,DatePicker} from 'antd-mobile';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail,datevali} from '../../utils/Validator.js'
import PropTypes from 'prop-types';
import options from '../../models/CityData.js'
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import moment from 'moment';
import 'moment/locale/zh-cn';
class StrateEdit extends React.Component{
		constructor(props){
		super(props);
		this.state={
			reginos:[],
			disable:true,
      end_at:null,
      start_at:null,
      option:[],
      store_tree:[],
      ism:JSON.parse(window.sessionStorage["ism"])
		}
	}
  getServer(){
    reqwest({
      url: window.host+'/api/pres',
      method: 'get',
      crossOrigin: true,
      // headers:AUTH_KEY,
      // contentType: 'application/json',
      data:{
        access_token:window.localStorage['token']
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      // sessionStorage['companies']=JSON.stringify(data.companies);
      // sessionStorage['material']=JSON.stringify(data.libs);
      this.setState({store_tree:data.regions})
    }).fail( (err, msg) =>{
       console.log(1)
       // this.setState({loading:true});
    })
  }
	patchserver(params={}){
		// console.log(data)
    let _this = this;
		reqwest({
      url: window.host+'/api/strategies/'+_this.state.ism.id,
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{ access_token:localStorage['token'],
        strategy:{title:params.theme,
          start_at:params.start_at,end_at:params.end_at,
          region_id:params.regions[0],province:params.province[0],city:params.province[1],area:params.province[2],
          rate:params.rate===undefined?0:params.rate/100,discount:params.discount===undefined?0:params.discount/100,rebate:params.rebate===undefined?0:params.rebate/100,pound:params.pound},
        }
    }).then((data) => {
      if(data.status=='success'){
          Toast.success(
          '保存成功',
          1,
          ()=>{
            window.location.hash='/hfive/strategies';
          }
        )
        
      }else{
        Toast.fail(
          data.msg,
          1
        )
      }
    }).fail( (err, msg) =>{
       Toast.offline('网络连接失败!!!', 1);
    });
	}
	handleSubmit(e){
		e.preventDefault();
    let _this=this;
    // this.props.form.getFieldError('cha_name')
    this.props.form.validateFields((err, values) => {
        console.log(values.regions);
        // let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g):null;
      if (!err  ) {
        console.log('Received values of form: ', values);
      	_this.patchserver(values)
      }
    });
	}
	componentWillMount(){
    let _end =new Date()
    this.getServer();
    if(this.state.start_at==null){
      console.log(_end)
      this.setState({end_at:moment(datevali(_end)+' +0800', 'YYYY-MM-DD Z').utcOffset(8)})
    }
		let _regions=[];
		if(!!sessionStorage['regions']){
			JSON.parse(sessionStorage['regions']).map(function(data,index){
				_regions.push({
					value:data.id,
					label:data.name
				})
			})
		}
		this.setState({reginos:_regions})
	}
  startOk(e){
    this.setState({end_at:moment(datevali(e._d)+' +0800', 'YYYY-MM-DD Z').utcOffset(8)})
  }
	render(){
		 const { getFieldProps , getFieldError} = this.props.form;
     console.log(this.state.ism)
     const {ism} = this.state;
		 const _this =this;
     let _regions=[]
     this.state.store_tree.map(function(data,index,obj){
      _regions.push({
        label:data.name,
        value:data.id
      })
    })
		 return(
			<div className={`${style.layout}`}>
				<List renderHeader={() => '编辑策略'} className={`${Reset.tel_list_header}`}>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('theme')}
	          onErrorClick={() => {
	            alert(getFieldError('theme').join('、'));
	          }}
            {...getFieldProps('theme',{
            	initialValue:ism.title,
            	rules:[{message:'请输入主题'}]
            })}
            placeholder="请输入主题"
          >主题</InputItem>
          <Picker data={_regions} cols={1} {...getFieldProps('regions',{
            initialValue:[ism.region_id],
          	rules:[{message:'请选择你的渠道'}]
          })} className={`${Reset.tel_picker}`} extra={<span>选择渠道</span>}>
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">渠道</List.Item>
          </Picker>
          <DatePicker
            className={`${Reset.tel_picker}`}
            mode="date"
            title="开始时间"
            extra={<span>开始时间</span>}
            clear
            error={!!getFieldError('start_at')}
            onErrorClick={() => {
              alert(getFieldError('start_at').join('、'));
            }}
            onOk={this.startOk.bind(this)}
            minDate={moment('2016-08-06 +0800', 'YYYY-MM-DD Z').utcOffset(8)}
            {...getFieldProps('start_at', {
            	initialValue:moment(datevali(ism.start_at) +'+0800','YYYY-MM-DD Z'),
            	rules:[{message:'请输入开始时间'}]
            })}
          >
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">开始时间</List.Item>
          </DatePicker>
          <DatePicker
            className={`${Reset.tel_picker}`}
            mode="date"
            title="结束时间"
            extra={<span>结束时间</span>}
            clear
            error={!!getFieldError('end_at')}
            onErrorClick={() => {
              alert(getFieldError('end_at').join('、'));
            }}
            minDate={this.state.end_at}
            {...getFieldProps('end_at', {
            	initialValue:moment(datevali(ism.end_at) +'+0800','YYYY-MM-DD Z'),
            	rules:[{message:'请输入结束时间'}]
            })}
          >
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">结束时间</List.Item>
          </DatePicker>
           <Picker   extra={<span>地址</span>} style={{textAlign:'left'}} clear
            className={`${Reset.tel_picker}`}
            error={!!getFieldError('province')}
            onErrorClick={() => {
              alert(getFieldError('province').join('、'));
            }}
            placeholder="选择地址"
            onOk={(e)=>{this.setState({disable:false});console.log(e)}}
            {...getFieldProps('province',{
            	initialValue:[ism.province,ism.city,ism.area],
              rules:[{message:'请选择地址'}]
            })}  title="选择地址" data={options} >
            <List.Item arrow="horizontal"
              className={`${Reset.list_extra} ${Reset.tel_input}`}
            >选择地址</List.Item>
          </Picker>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('rate')}
	          onErrorClick={() => {
	            alert(getFieldError('rate').join('、'));
	          }}
            {...getFieldProps('rate',{
            	initialValue:ism.rate*100,
            	rules:[{message:'请输入提成',}]
            })}
            extra="%"
            placeholder="提成"
          >提成</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('discount')}
	          onErrorClick={() => {
	            alert(getFieldError('discount').join('、'));
	          }}
            {...getFieldProps('discount',{
            	initialValue:ism.discount*100,
            	rules:[{message:'请输入折扣'}]
            })}
            extra="%"
            placeholder='折扣'
          >折扣</InputItem>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('rebate')}
            onErrorClick={() => {
              alert(getFieldError('rebate').join('、'));
            }}
            {...getFieldProps('rebate',{
            	initialValue:ism.rebate*100,
              rules:[{message:'请输入返利'}]
            })}
            extra="%"
            placeholder='返利'
          >返利</InputItem>
          <InputItem
            clear
            className={`${Reset.tel_input}`}
            error={!!getFieldError('pound')}
            onErrorClick={() => {
              alert(getFieldError('pound').join('、'));
            }}
            {...getFieldProps('pound',{
            	initialValue:ism.pound,
              rules:[{message:'请输入策略优先级'}]
            })}
            placeholder='策略优先级'
          >策略优先级</InputItem>
          <List renderHeader={() => '备注'} style={{background:'#f5f5f9'}} className={`${Reset.tel_list_header}`}>
	          <TextareaItem
              className={`${Reset.tel_textarea}`}
	            {...getFieldProps('remark', {
	              initialValue: '备注'
	            })}
	            rows={5}
	            count={100}
	          />
	        </List>
        </List>
        <Button className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>保存</Button>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}

const StrateForm = createForm()(StrateEdit);
export default connect()(StrateForm)